﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;
using Domain;
using System.ComponentModel;
using System.Runtime.Remoting.Messaging;

namespace DAO
{
    public static class Email
    {
        private const bool EMAIL_ENABLED = true;
        private const string fromAddress = "hiddencode.2.0@gmail.com";

        public static bool Send(string strMailContent,string toAddress, string strMailSubject)
        {
            try
            {

                if (!EMAIL_ENABLED)
                    return true;

                //string strMailContent = "Welcome new user";
                
                //string toAddress = "newuser@hisdomain.com";

                //toAddress = fromAddress; // SACAR!

                MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
                //mailMessage.Bcc.Add("inkrajesh@hotmail.com"); // put your id here
                mailMessage.Subject = strMailSubject;

                //string contentId = "image1";
                //string path = Server.MapPath(@"images/Logo.jpg"); // my logo is placed in images folder
                //LinkedResource logo = new LinkedResource(path);
                //logo.ContentId = "companylogo";
                // done HTML formatting in the next line to display my logo
                AlternateView av1 = AlternateView.CreateAlternateViewFromString(EncabezadoMail() + strMailContent + PieMail(), null, MediaTypeNames.Text.Html);
                //av1.LinkedResources.Add(logo);

                mailMessage.AlternateViews.Add(av1);
                mailMessage.IsBodyHtml = true;

                
                //string parameter = "BLA";
                //smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                //smtp.SendAsync(mailMessage,parameter);
                //smtp.Send(mailMessage);
                SendAsync(mailMessage);


                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
            finally{
                
            }

        }

        private static SmtpClient GetSmtp(){
            SmtpClient smtp = new SmtpClient();

            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new System.Net.NetworkCredential(fromAddress, "grupo513");

            return smtp;
        }

        #region SendSync
        private static void SendSync(MailMessage message){
            SmtpClient smtp = GetSmtp();
            smtp.Send(message);
        }
        #endregion

        #region SendAsync
        public static void SendAsync(MailMessage message)
        {
            AsyncMethodCaller caller = new AsyncMethodCaller(SendMailInSeperateThread);
            AsyncCallback callbackHandler = new AsyncCallback(AsyncCallback);
            caller.BeginInvoke(message, callbackHandler, null);
        }
        
        private delegate void AsyncMethodCaller(MailMessage message);

        private static void SendMailInSeperateThread(MailMessage message)
        {
            try
            {
                SmtpClient client = GetSmtp();
                client.Timeout = 20000; // 20 second timeout... why more?
                client.Send(message);
                message.Dispose();

                // If you have a flag checking to see if an email was sent, set it here
                // Pass more parameters in the delegate if you need to...
            }
            catch (Exception e)
            {
                // This is very necessary to catch errors since we are in
                // a different context & thread
                //Elmah.ErrorLog.GetDefault(null).Log(new Error(e));
            }
        }

        private static void AsyncCallback(IAsyncResult ar)
        {
            try
            {
                AsyncResult result = (AsyncResult)ar;
                AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;
                caller.EndInvoke(ar);
            }
            catch (Exception e)
            {
                //Elmah.ErrorLog.GetDefault(null).Log(new Error(e));
                //Elmah.ErrorLog.GetDefault(null).Log(new Error(new Exception("Emailer - This hacky asynccallback thing is puking, serves you right.")));
            }
        }
        #endregion

        public static bool goSendPublicacion(Publicacion whatPub, Usuario toUsr) {
            return Send("<div style='text-align:right;'>" +
                        "Nro Publicación: <b>" + whatPub.Id.ToString() + "</b>" +
                        (whatPub.FechaBaja.HasValue ? "- <b>¡ESTA PUBLICACION FUE DADA DE BAJA!</b>" :
                        (whatPub.FechaCaducidad.HasValue ? "- Caduca el <b>" + whatPub.FechaCaducidad.Value.ToString("dd/MM/yyyy") + "</b>" : string.Empty))
                        + "<br /><br />" +
                        "</div>" +
                        System.Web.HttpUtility.HtmlDecode(whatPub.UltimaRevision.Datos) +
                        "<div style='margin-top:10px;color:gray;'>Recordá o llevá anotado tu PIN para registrar consumos.<br /> En caso de necesitarlo, el comercio por seguridad va a solicitarlo para validar tu identidad.</div>",
                        toUsr.EMail, 
                        whatPub.Descripcion);
        }

        public static bool goSendPublicacion(long whatIdPub, Usuario toUsr)
        {
            List<Publicacion> lp = PublicacionDAO.Traer(whatIdPub, null, null);
            if (lp.Count > 1 || lp.Count == 0)
                return false;

            Publicacion whatPub = lp[0];

            return goSendPublicacion(lp[0], toUsr);
        }

        private static string EncabezadoMail()
        {

            return "<div style='background-color:#59C7D3; border-bottom:1px solid gray;text-align:center;padding-top:1px;'><h3>Hidden Code 2.0</h3> </div><div style='padding-top:12px;padding-bottom:12px;'>";
        }

        private static string PieMail()
        {
            return "</div><div style='background-color:#59C7D3; border-top:1px solid gray;text-align:right;'><a href='http://www.facebook.com/hidden.code.2.0' class='icon-16 facebook'rel='nofollow' target='_blank' title='Facebook' style='text-decoration:none;'><img src='http://cdn1.iconfinder.com/data/icons/web2/Icons/FaceBook_48x48.png'/></a><a href='http://www.twitter.com/hidden_code_2_0' class='icon-16 twitter' rel='nofollow' target='_blank' title='Twitter' style='text-decoration:none;'><img src='http://cdn1.iconfinder.com/data/icons/web2/Icons/Twitter_48x48.png'/></a><span style='display:block;color:gray'>fueled by Underground Systems</span></div>";
        }
    }
}
